package reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 使用指定的构造器实例化对象
 */
public class ReflectDemo3 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Person p = new Person("李四");
        System.out.println(p);

        //1获取类对象
        Class cls = Class.forName("reflect.Person");
        /*
            通过类对象获取某个特定的构造器

            Constructor构造器对象，反射对象之一
            它的每一个实例用于表示一个类上的某个构造器
         */
//        Constructor c = cls.getConstructor();//获取无参构造器Person()

        //Person(String)
        Constructor c = cls.getConstructor(String.class);
        Object obj = c.newInstance("王五");//new Person("王五");
        System.out.println(obj);

        //Person(String,int)
        Constructor c2 = cls.getConstructor(String.class,int.class);
        Object o2 = c2.newInstance("赵六",23);//new Person("赵六",23);
        System.out.println(o2);
    }
}










